package com.qfedu.edu.seckill.aclservice.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.edu.bo.SecurityUser;
import com.qfedu.edu.po.Perm;
import com.qfedu.edu.po.Role;
import com.qfedu.edu.po.User;
import com.qfedu.edu.seckill.aclservice.mapper.UserMapper;
import com.qfedu.edu.seckill.aclservice.mapper.UserRoleMapper;
import com.qfedu.edu.seckill.aclservice.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.edu.vo.LoginVo;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaobobo
 * @since 2025-03-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService , UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String loginVoJsonStr) throws UsernameNotFoundException {
        LoginVo loginVo = JSON.parseObject(loginVoJsonStr, LoginVo.class);
        String username = loginVo.getUsername();
        if (StringUtils.isEmpty(username)){
            throw new UsernameNotFoundException("用户名不对");
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user==null){
            throw new UsernameNotFoundException("用户没有找到");
        }
        //执行到这里表明用户已经查询到了
        List<Role> roleList=userRoleMapper.findRoleByUserId(user.getUserId());
        List<Perm> permList=userRoleMapper.findPermissionByUserId(user.getUserId());
        //将权限和角色信息放到集合中
        List<String> roleAndPermList=wrapRoleAndPerm(roleList,permList);
        SecurityUser securityUser = new SecurityUser();
        securityUser.setUser(user);
        securityUser.setRoleAndPermList(roleAndPermList);

        return securityUser;
    }

    /**
     * 将权限和角色信息放到集合中
     * @param roleList
     * @param permList
     * @return
     */
    private List<String> wrapRoleAndPerm(List<Role> roleList, List<Perm> permList) {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < roleList.size(); i++) {
            Role role = roleList.get(i);
            list.add("ROLE_"+role.getRoleName());
        }
        for (int i = 0; i < permList.size(); i++) {
            Perm perm = permList.get(i);
            list.add(perm.getPermVal());
        }
        return list;
    }
}
